package com.wswy.wzcx.widget.utils;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.NonNull;
import android.text.TextPaint;
import android.text.style.ReplacementSpan;

import android.util.Log;
import com.blankj.utilcode.util.SizeUtils;

public class VerticalCenterSpan extends ReplacementSpan {

  private static final String TAG = "VerticalCenterSpan";

  private float fontSizeSp;
  private int color;

  public VerticalCenterSpan(float fontSizeSp, int color) {
    this.fontSizeSp = fontSizeSp;
    this.color = color;
  }

  @Override
  public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
    text = text.subSequence(start, end);
    Paint p = makeTextSpan(paint);
    return (int) p.measureText(text.toString());
  }

  @Override
  public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
    text = text.subSequence(start, end);
    Paint p = makeTextSpan(paint);
    Paint.FontMetricsInt fm = p.getFontMetricsInt();
    canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), p);    //使字体居中
  }

  private TextPaint makeTextSpan(Paint srcPaint) {

    TextPaint paint = new TextPaint(srcPaint);
    paint.setTextSize(SizeUtils.sp2px(fontSizeSp));
    paint.setColor(color);
    return paint;
  }
}